import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NzMessageService, NzModalRef, NzModalService, UploadFile } from 'ng-zorro-antd';
import { FormBuilder, FormControl, FormGroup,  Validators } from '@angular/forms';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { UtilService } from '@core/services/util.service';
import * as $ from 'jquery';
import { reader }from '../../../../../assets/js/rdapi.js';
import { Base64Service } from '@core/services/base64.service';
import { TakephotoComponent } from '@shared/components/takephoto/takephoto.component';

@Component({
  selector: 'landloard-add',
  templateUrl: './landlord-add.component.html',
  styleUrls:["./landlord-add.component.less"]
})
export class LandlordAddComponent implements OnInit {
  @ViewChild('treedom',{ static: false }) treedom:any;
  pIdList:any[]=[];
  value: any ;
  validateForm!: FormGroup;
  showForm=true;
  isLoading:boolean=false;
  _param:any;
  show=false;
  avatarUrl:string="";
  previewVisible = false;
  previewImage: string | undefined = '';
  g_device:string="00";
  g_isOpen:boolean= false;
  g_wantFunc:number=0;
  cardNo:string;
  nodes=[];
  maxSize:number=1000;//图片最大为1M
  maxWidth:number=640;
  maxHeight:number=480;
  isAllow:boolean=true;//图片是否超出限制
  timeout:any="";

  desNum="";
  readData=0;//读出的数据
  pwd="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";//密钥
  num=0;//web认证的次数 现在设置为两次，两次不成功的话就不再继续
  inNum=0;//代表创建两个二进制文件
  select=0;//复位
  random=0;//获取随机数
  delfile=0;//擦除MF下的数据
  createSK=0;//创建密钥文件
  sk=0;//增加外部认证密钥
  createTwo=0;//创建二进制文件
  writeFile=0;//写入二进制文件
  readFile=0;//读取二进制文件


  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: UploadFile }){
    console.log(info);
    //判断图片是否超出1M
    // this.testMaxSize(info.file);
    // if(this.isAllow){//未超出1M
    //   this.getBase64(info.file!.originFileObj!, (img: string) => {
    //     this.avatarUrl = img;
    //     this.show=true;
    //   });
    // }else{//超出1M,压缩图片
    //   this.getBase64(info.file!.originFileObj!, (img: string) => {
    //     let imgObj=new Image();
    //     imgObj.src=img;
    //     imgObj.onload=()=>{
    //       const { width:originWidth,height:originHeight } = imgObj;
    //       console.log(originHeight,originWidth);
    //       this.compressImg(originWidth,originHeight,imgObj);
    //     }
    //   });
    // }
    this.getBase64(info.file!.originFileObj!, (img: string) => {
      let imgObj=new Image();
      imgObj.src=img;
      imgObj.onload=()=>{
        const { width:originWidth,height:originHeight } = imgObj;
        console.log(originHeight,originWidth);
        this.compressImg(originWidth,originHeight,imgObj);
      }
    });
   
  }

  //等比例缩放，canvas压缩图片
  compressImg(originWidth:number,originHeight:number,img){
    let targetWidth=originWidth;
    let targetHeight=originHeight;
    // 等比例计算超过最大限制时缩放后的图片尺寸
    if (originWidth > this.maxWidth || originHeight > this.maxHeight) {
      if (originWidth / originHeight > 1) {
      // 宽图片
      targetWidth = this.maxWidth
      targetHeight = Math.round(this.maxWidth * (originHeight / originWidth))
      } else {
      // 高图片
      targetHeight = this.maxHeight
      targetWidth = Math.round(this.maxHeight * (originWidth / originHeight))
      }
    }

    // 创建画布
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    
    // 设置宽高度为等同于要压缩图片的尺寸
    canvas.width = targetWidth
    canvas.height = targetHeight
    context.clearRect(0, 0, targetWidth, targetHeight)
    //将img绘制到画布上
    context.drawImage(img, 0, 0, targetWidth, targetHeight)
    let base64=canvas.toDataURL("image/jpeg",0.8);
    this.avatarUrl = base64;
    this.show=true;
  }

   //判断图片大小是否超出限制
  //  testMaxSize(file){
  //   if(file){
  //     let size=file.size;//这里读到的是字节数
  //     let max_size=this.maxSize * 1024 ; //转化为字节
  //     if(size > max_size){
  //      // this.msg.error("图片最大为1M,超出大小!");
  //       this.isAllow=false;
  //     }else{
  //       this.isAllow=true;
  //     }
  //   }
  // }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }
 
  submitForm(data) {
    console.log(data);
    // if(!this.isAllow){
    //   this.msg.error("图片最大为2M,超出大小!");
    //   return;
    // }
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
      if(this.validateForm.controls[key].invalid){
        return;
      }
    }
    let nodes=this.treedom.getCheckedNodeList();
    if(nodes.length == 0){
      this.msg.error("请选择楼栋!");
      return;
    }
    let list= this.getCheckedNodes(nodes);
    let pIdArr=Array.from(new Set(this.pIdList));
    let houseManagerList=[];
    for(let item of pIdArr){
      let obj={
        houseId:item,
        roomId:""
      }
      let roomList=[];
      for(let current of list){
        if(item == current.pId){
          roomList.push(current.id);
        }
      }
      obj.roomId=roomList.join(",");
      houseManagerList.push(obj);
    }
    if(this.avatarUrl.indexOf("data:image") == -1){
      this.avatarUrl=this.base64.getDefaultBase64();
    }
    const body: any = data;
    body.hoseManagerList=houseManagerList;
    body.idCardPic=this.avatarUrl.replace(/^data:image\/\w+;base64,/, '');
    body.papersType=1;
    //body.cardNo == undefined ? "" : body.cardNo;
    if(body.cardNo != undefined && body.cardNo != "" && body.cardNo != null){
      body.cardId = body.cardNo;
    }
    if(body.xnCardNo != undefined && body.xnCardNo != "" && body.xnCardNo != null){
      body.cardNo = body.xnCardNo;
    }
    console.log(body);
  this.http.post(this.api.manager.landlordRegister.url,body).subscribe((res:any) => {
    console.log(res)
    if (res.status === '200') {
      this.msg.success('操作成功');
      this.modalRef.triggerOk();
    } else {
      this.msg.error(res.message)
    }
  })
}
//拍照
takePhoto() {
 let a = this.modal.create({
    nzTitle:  '拍照',
    nzContent: TakephotoComponent,
    nzWidth: 600,
    nzFooter:null
  })
  a.afterClose.subscribe(res=>{
    if(res){
      this.avatarUrl = res;
      this.show=true;
    }else{
      const modalInstance = a.getContentComponent(); // 获取模态框实例
      if(modalInstance.stream){
        modalInstance.stream.getTracks()[0].stop()
      }
    }
  })
}


//扁平化树形数据
getCheckedNodes(checkedNodeList:any){
  let that=this;
  let list=[];
  this.pIdList=[];
  for(let item of checkedNodeList){
    if(item.origin.pId != ""){
     list.push({
        "id":item.origin.id,
        "pId":item.origin.pId
      })
      that.pIdList.push(item.origin.pId);
    }
    if(item.origin.children && item.origin.children.length > 0){
      for(let current of item.origin.children){
        list.push({
          "id":current.id,
          "pId":current.pId
        })
        that.pIdList.push(current.pId);
      }
    }
  }
  return list;
}

constructor(
  private api: ApiService,
  private http: HttpClient,
  private msg: NzMessageService,
  private modalRef: NzModalRef,
  private modal: NzModalService,
  private util: UtilService,
  private base64: Base64Service,
  private fb: FormBuilder
) {  }


//读取身份证信息
readIdCard(){
  let that=this;
  $.ajax({
    url:"http://127.0.0.1:18889/api/readCard",
    type:"post",
    success:function(data){
      let arr=JSON.parse(data);
      if(arr.resultFlag == -1){
        that.msg.error(arr.errorMsg);
      }else if(arr.resultFlag == 0){
          that.validateForm.patchValue({
            infoName:arr.resultContent.partyName,
            infoSex:""+arr.resultContent.gender,
            idCardNo:arr.resultContent.certNumber,
            infoBirthday:that.getDate(arr.resultContent.bornDay),
            infoNationName:arr.resultContent.nation,
            papersAddress:arr.resultContent.certAddress,
            papersAuthority:arr.resultContent.certOrg,
            papersValidBegin:that.getDate(arr.resultContent.effDate),
            papersValidStop:that.getDate(arr.resultContent.expDate)
          })
          that.avatarUrl="data:image/jpg;base64,"+arr.resultContent.identityPic;
          that.show=true;
      }
    }
  })
}


  ngOnInit(): void {
    let that=this;
    this.connectIdCard();
    // this.getHouses();
    this.validateForm = this.fb.group({
      infoPeopleType:["",[Validators.required]],
      infoName: [null, [Validators.required]],
      infoSex: ["", [Validators.required]],
      idCardNo:[null,[Validators.required]],
      infoBirthday:[null,[Validators.required]],
      infoNationName:[null,[Validators.required]],
      papersAddress:[null,[Validators.required]],
      papersAuthority:[null,[Validators.required]],
      papersValidBegin:[null,[Validators.required]],
      papersValidStop:[null,[Validators.required]],
      infoMobile:[null,[Validators.required]],
      cardNo:[null],
      cardCode:[null],
      xnCardNo:[null]
    });
    
    if(reader.SocketOpen){
      this.connect();
    }else{
      reader.createSocket();
      setTimeout(()=>{
        this.connect();
      },200)
    }
    reader.onResult((rData:any)=>{
      console.log(rData)
      this.inNum++;
      if(rData.strCmdCode == "1203"){
        let str=rData.strData;
        let a=str.substring(str.length-4,str.length);
        if(a != "9000" ){//证明出现错误
          if(this.delfile == 1){//代表密钥错误，需要用新的密钥，然后获取并发送八字节加密数据
            this.select=1;
            this.delfile=0;
            this.pwd="0123321456654789987ABCDEFFEDCBC1";//用新的密钥去认证
            if(this.num == 2){//如果认证两次依然错误的话，则不再继续
              this.msg.error('密钥错误')
              return;
            }
          }else{
            return;
          }
        }
      }

      if(this.readData == 1){//代表读取二进制文件
        this.checkCard();
       let n=rData.strData.slice(0,16);
       this.validateForm.patchValue({
        xnCardNo:n
      })
       this.readData=0;
      }
      
      if(this.select == 1 ){//获取随机数 已复位
        this.getRandom();
        this.random=1;
        this.select=0;
      }else if(this.random == 1 ){//发送八字节加密数据
        //获取八字节加密数据，然后发送八字节加密数据
        this.getDesNum(rData.strData.slice(0,16)).then((res)=>{
          this.getNumber();
        });
        this.num++;
        this.delfile=1;
        this.random=0;
      }else if(this.delfile == 1 ){
        this.delData();
        this.createSK=1;
        this.delfile=0;
      }else if(this.createSK == 1 ){
        this.createFile();
        this.sk=1;
        this.createSK=0;
      }else if(this.sk == 1 ){
        this.addSK();
        this.createTwo=1;
        this.sk=0;
      }else if(this.createTwo == 1 ){
        this.createHex();
        this.writeFile=1;
        this.createTwo=0;
        this.inNum=0;
      }else if(this.writeFile == 1 && this.inNum == 2){//index=2代表两个二进制文件已经创建完成，然后执行写二进制文件
        this.writeHex();
        this.writeFile=0;
        this.readFile=1;
        this.inNum=0;
      }else if(this.readFile == 1 && this.inNum == 2){//读取二进制文件  index=2代表两个二进制文件已经写入完成，可以执行读二进制文件
        this.readHex();
        this.readFile=0;
        this.readData=1;
      }

      switch(rData.strCmdCode){
        case "0007":
          if(rData.strStatus != "00"){
            this.msg.error("连接设备失败!");
          }else{
            this.g_isOpen=true;
            console.log("连接成功")
          }
          break;
        case "1001":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
             case 1:
              reader.send(this.g_device + "1002"); //TyA_Anticollision
              break;
          }
          break;
        case "1002":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
              case 1 :
                // that.validateForm.patchValue({
                //   cardNo:rData.strData
                // })
                // this.cardNo=rData.strData;
                // this.checkCard();
              break;
          }
          break;
          case "1202"://复位
            this.cardNo=rData.strData.slice(0,8);
            console.log("选择MF");
            reader.send(this.g_device + "1203" + "00A40000023F00");//选择MF
            this.select=1;
          break;
      }
     
    })
  }

  ngOnDestroy(){
    reader.Disconnect();
  }
  onKey(event){
    let fn=this.debounce(this.getHouses,1000,event.target.value)
    fn()
  }
  debounce(fn,wait,data){
    const self=this
    return ()=>{
      if(self.timeout) clearTimeout(self.timeout)
      self.timeout=setTimeout(()=>{
        fn.call(self,data)
      },wait)
    }
  }
  //获取楼栋房间列表
  getHouses(val): void{
    this.isLoading = true
    this.http.post(this.api.manager.queryUnitHouse.url,{"areaParentAllName":val}).subscribe( (res:any) => {
      if (res.status === '200' && res.data && res.data.list.length > 0) {
        let list=[];
        for(let item of res.data.list){
          list.push({
            key:item.id,
            pId:item.areaId == undefined ? "" : item.areaId,
            title:item.areaParentAllName,
            id:item.id,
            value:item.id
          })
          for(let current of item.roomList){
            list.push({
              key:current.id,
              pId:current.areaId,
              title:""+current.roomNumber,
              id:current.id,
              value:current.id
            })
          }
        }
        // console.log(list);
        this.nodes=this.util.getTreeNodeOption(list);
        document.getElementById('tree').click()
        setTimeout(() => {
          document.getElementById('tree').click()
        }, 50);
        //this.showForm = true;
      }
      this.isLoading=false;
    })
  }

  connectIdCard(){
    $.ajax({
      url:"http://127.0.0.1:18889/api/connect",
      type:"post",
      success:function(data){
        console.log(data);
      }
    })
  }

  //获取标准日期格式
  getDate(str:string){
    const year=str.substring(0,4);
    const month=str.substring(4,6);
    const date=str.substring(6,8);
    return year+"-"+month+"-"+date;
  }

//卡号输入框失焦验证卡号是否已被绑定
  iptBlur(){
    this.checkCard();
  }

  //读卡或者输完卡号之后，检查此卡是否已经被绑定
checkCard(){
  if(this.cardNo == "" || this.cardNo == undefined){
    return;
  }
  const that=this;
  this.http.get(this.api.doorCard.checkCard.url+this.cardNo).subscribe((res:any)=>{
    console.log(res);
    if(res.status == 200){
      if(res.data != null && res.data.personId != ""){
            this.msg.error("此卡已经被绑定!");
            setTimeout(function(){
              that.cardNo="";
              that.validateForm.patchValue({
                xnCardNo:""
              })
            },1000);
        }
    }
  })
}

connect(){
	reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
	reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
	reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
  this.LedGreen();
  setTimeout(()=>{this.LedRed()},200);
  reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
}
/**
 * Turn on the green light
 * (亮绿灯)
**/
LedGreen()
{
  reader.send(this.g_device + "0107" + "02"); 
}

/**
 * Turn on the red light
 * (亮红灯)
**/
LedRed()
{
  reader.send(this.g_device + "0107" + "01"); 
}

read(){
  // if(this.g_isOpen != true){
  //   this.message.error("请连接读卡器!");
  //   return;
  // }
  this.num=0;
  this.selectMF();
}

//复位之后才能发送cos命令
selectMF(){
  console.log("复位");
  console.log(1);
  this.select=0;
  reader.send(this.g_device + "1202" + "26");//复位
}

//获取四字节随机数
getRandom(){
  console.log("获取八字节随机数")
  console.log(2);
  reader.send(this.g_device + "1203" + "0084000008");//获取四字节随机数
}

//发送八字节加密数据
getNumber(){
  console.log("发送八字节加密数据");
  console.log(3);
  console.log(this.desNum)
  reader.send(this.g_device + "1203" + "0082000008" + this.desNum);
}
//擦除MF下的数据
delData(){
  console.log("擦除MF下的数据");
  console.log(4);
  //擦除MF下的数据
  reader.send(this.g_device + "1203" + "800E000000");
}
//建立密钥文件
createFile(){
  //建立密钥文件
  console.log("建立密钥文件");
  console.log(5);
  reader.send(this.g_device + "1203" + "80E00000073F005001F1FFFF");
}
//增加外部认证密钥
addSK(){
  console.log("增加外部认证密钥");
  console.log(6);
  reader.send(this.g_device + "1203" + "80D401001539F0F1AADD"+"0123321456654789987ABCDEFFEDCBC1");
  //reader.send(g_device + "1203" + "80D401000D39F0F1AADD"+"FFFFFFFFFFFFFFFF");
}
//创建二进制文件
createHex(){
  console.log("创建二进制文件");
  console.log(7);
  reader.send(this.g_device + "1203" +"80E0001F07280020F0F1FFFF");//31号文件
  reader.send(this.g_device + "1203" +"80E0001A07280020F0F1FFFF");//26号文件
  
}
//写二进制文件
writeHex(){
  console.log("写二进制文件");
  console.log(8);
  this.getDesNum(this.cardNo+"00000000").then((res)=>{
    console.log('虚拟卡号',this.desNum)
    reader.send(this.g_device + "1203" +"00D69F0008"+"8F4C3814C3B499A9");//31号文件
    reader.send(this.g_device + "1203" +"00D69A0008"+this.desNum);//26号文件
  })
 
}
//读二进制文件
readHex(){
  console.log("读二进制文件");
  console.log(9);
  reader.send(this.g_device + "1203" +"00B09A0010");
}

//获取八字节加密数据
getDesNum(randomNum){
 return  new Promise((resolve)=>{
    this.http.post("/core/door/card/desCard?data="+randomNum+"&password="+this.pwd,{}).subscribe((res:any)=>{
      console.log(res)
      this.desNum=res.data
      resolve(res.data)
    })
  })
}


//读卡
// readCpu(){
//   if(this.g_isOpen != true){
//     this.msg.error("请连接读卡器!");
//     return;
//   }
//   //Start read UID
//   reader.send(this.g_device + "1001" + "52"); //TyA_Request
//   this.g_wantFunc = 1;  
//   reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
// }

// //连接读卡器
// Connect(){
// 	reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
// 	reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
// 	reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
//  this.LedGreen();
//  let that=this;
//   setTimeout(function(){that.LedRed()},200); 
//   reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
// }

// LedGreen(){
//  reader.send(this.g_device + "0107" + "02"); 
// }

// LedRed(){
//   reader.send(this.g_device + "0107" + "01"); 
// }

}
